import cv2
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv2.imread('img/screen1.bmp')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread('img/hat3.png', 0)
w, h = template.shape[::-1]

methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']


meth = methods[4]
#for meth in methods:
method = eval(meth)
print("method:",meth)
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold = 0.72
loc = np.where(res >= threshold)
print(" Points:")
for pt in zip(*loc[::-1]):
    print(" ",pt)
    cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)

pts = (loc[::-1])
if len(pts[0])>0:
    maxX, minX, maxY, minY = max(pts[0]),  min(pts[0]), max(pts[1]), min(pts[1])
    print(maxX,minX,maxY,minY)
    print(" diff X:",maxX-minX,", diff Y:",maxY-minY)

# cv2.imwrite('res.png',img_rgb)
# cv2.imshow("output", img_rgb)
#if cv2.waitKey(0) == 27:
#    cv2.destroyAllWindows()
